import api from '../../utils/api';
import store from '../../utils/store';

Page({
  data: {
    courses: [],
    loading: true,
    error: null
  },

  onLoad() {
    this.unsubscribe = store.subscribe(state => {
      this.setData({ courses: state.courses });
    });
    this.fetchCourses();
  },

  onUnload() {
    this.unsubscribe && this.unsubscribe();
  },

  async fetchCourses() {
    try {
      const courses = await api.getCourses();
      store.setState({ courses });
      this.setData({ loading: false });
    } catch (error) {
      this.setData({ 
        loading: false,
        error: error.message 
      });
    }
  },

  onPullDownRefresh() {
    this.fetchCourses().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});